from flask import Flask, render_template, request, redirect

app = Flask(__name__)
@app.route("/")
def scrawl():
    return render_template("scrawl.html")


@app.route("/login",methods=['POST','GET'])
def login():
    username = request.form['username']
    userpwd = request.form['userpwd']
    if username == 'admin':
        if userpwd == 'admin123':
            return redirect("scrawl")
        else:
            return redirect("/")
    else:
        return redirect("/")

@app.route("/scrawl")
def scrawler():
    return render_template("scrawl.html")

@app.route("/start",methods=['POST','GET'])
def start():
    name=request.form['targetname']
    url=request.form['targeturl']
    print(name)
    #调用爬虫函数
    return str(crawl(url,selector="p"))

import requests
from bs4 import BeautifulSoup
def crawl(url,selector):
    headers={
        'user-agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.12022 SLBChan/103"
    }
    #获取源代码
    htmlcodes = requests.get(url,headers=headers).text
    #解析源代码
    bs = BeautifulSoup(htmlcodes,'html.parser')
    #根据选择器返回文本
    return [item.text for item in bs.select(selector=selector)]

if __name__ == '__main__':
    app.run()
